/******************************************************************************************
Use Case name and Id: 1.0 View Group Ride Event 
by Michael Puzon,  lastupdated March 20, 2010
Class: COIN 71

Functional Specification

The page issues a get request to process_viewride.php, which issues back data in json format. The data is then built up in an array of custom Ride objects. This array can then be sorted by date or by ride ratings.

Web Master Maintenance:
******************************************************************************************
Web master may update a different php servlet by modifying getData() function, and changing the process_viewride.php parameter.

*/

//Ride object to be used by global var ridedata later on
function Ride(title, date, location, detail, rating, leadname, leadcontact){
	this.title = title;
	this.date = date;
	this.location = location;
	this.detail = detail;
	this.rating = rating;
	this.leadname = leadname;
	this.leadcontact = leadcontact;
}

//Global var ridedata that will house all ride data 
var ridedata;

//Global var sortorder for ascending or descending sort
var sortdata = {
	lastsorted : "date",
	sortorder : "asc"
};

//outputs content in the output div
//element- the kind of element, usually p for paragraph
//content- the text of the content, id-id of element
function outputDiv(element, content, id){
	var output = document.getElementById("output");
	if (id ==  undefined)
		id = "";
	addNode(output, element, id, content);	
}

//outputs content with a link in the output div
//parcontent- the text of the content
//linkcontent- the text of the link content
//href- the address of the link
function outputLink(href, parcontent, linkcontent){
	var output = document.getElementById("output");
	var parnode = addNode(output, "p", "", parcontent);	    
	var linknode = addLink(parnode, "", linkcontent);
	linknode.setAttribute("onclick", href);
}

//outputs date in a readable format
function outputDate(fulldate){
	return fulldate.toDateString() + " " + fulldate.toLocaleTimeString();
}

//sorts the ridedata array according to selected option in ridesort and calls listRides
//it uses the global var sortdata to determine whether to use asc or desc order
function sortList(){
	var chosenSort = document.getElementById("ridesort").value;			
	if (chosenSort == "date"){
		if (sortdata.lastsorted == "date"){
			if  (sortdata.sortorder == "asc"){
				sortdata.sortorder = "desc";
				ridedata.sort(compareDateStr2);
			}else{
				sortdata.sortorder = "asc";
				ridedata.sort(compareDateStr);
			}
		}else{
			sortdata.lastsorted = "date";
			ridedata.sort(compareDateStr);
		}
	}
	else{
		if (sortdata.lastsorted == "rides"){
			if  (sortdata.sortorder == "asc"){
				sortdata.sortorder = "desc";
				ridedata.sort(compareRideStr2);
			}else{
				sortdata.sortorder = "asc";
				ridedata.sort(compareRideStr);
			}
		}else{
			sortdata.lastsorted = "rides";
			ridedata.sort(compareRideStr);
		}
	}
   	listRides(ridedata);
}


//initializes ride data with data from json response
//sets ride data to null if error response
function initRideData(response){
	if (response == null){
		outputDiv("p", "Error Encountered: Could not connect to server at this time");
		ridedata = null;
		return;
	}	
	if (!response.success){
		ridedata = null;
		outputDiv("p", "Error Encountered: " + response.message);
		return;
	}
	rideArray = new Array();
	for (x in response.fields)  {
		details = newLine(response.fields[x].detail);
	
		title = response.fields[x].title;
		date = parseDate(response.fields[x].date);
		loc = response.fields[x].location;		
		rating = parseField("Ride Rating:", details);
		leadname = parseField("Ride Leader:", details);
		leadcontact = parseField("Contact Details:", details);
		addtldetails = parseField("Additional Details:", details);
		var newride = new Ride(title, date, loc, addtldetails, rating, leadname, leadcontact);
		rideArray[x] = newride;
	}
	ridedata = rideArray;
}

//parses date from json response
function parseDate(fulldate){   
	yr = fulldate.substr(0,4);
	mon = fulldate.substr(5,2);
	day = fulldate.substr(8,2);
	hour = fulldate.substr(11,2);
	minute = fulldate.substr(14,2);
	newdate = new Date();
	newdate.setFullYear(yr,(mon - 1),day);
	newdate.setHours(hour,minute,0);	
	return newdate;
}

//parses each field from json description response
//uses regular expression to extract each field
function parseField(compare, description){
	if (description == "")
		return "";
	var patt = new RegExp(compare + ".*\\n", 'i');	
	var match = description.match(patt);
	if (match == null)
		return "";
	else{
		var matchstr = new String(match);		
		return matchstr.substr(compare.length);
	}
}

//outputs ride data in a list form, also outputs number of ride events
function listRides(ride_data){
	$("#output").empty();
	$("#tblOut").empty();
	var pastrides = document.getElementById("pastrides");
	pastrides = pastrides.checked;
	var today = new Date();
	outputDiv("p", ride_data.length + " events found.", "eventsfound");
	var num = 1;
	for (x in ride_data)  {
		if (!pastrides && (ridedata[x].date<today))
			continue;		
		outputDiv("h3", num +  " " + ridedata[x].title);       		
		outputDiv("p", "Date : "   + outputDate(ridedata[x].date));
		
        outputLink("openMyModal('gmap.php?addr=" + escape(ridedata[x].location) + "');return false;", "Location : "   + ridedata[x].location + " ", "Show Map");
		outputDiv("p", "Details : "   + ridedata[x].detail);
		outputDiv("p", "Ride Rating : "   + ridedata[x].rating);
		outputDiv("p", "Ride Leader : "   + ridedata[x].leadname);
		outputDiv("p", "Contact Details : "   + ridedata[x].leadcontact);		
		num++;
	}	
	if (num == 26)
		$("#eventsfound").html("<p>Last " + (num - 1) + " events found.</p>");
	else
		$("#eventsfound").html("<p>" + (num - 1) + " events found.</p>");
}

//uses jquery ajax get function to process_viewride.php
//data returned is in json format
//if php servlet encounters unspecified error, response is usually in html, 
//that is why there is a check for { in initial data
//data is initially sorted by date, and data is then outputted using listRides function
function getData(){
	$("#output").empty();
	$.get("process_viewride.php", "",				
	function(data){  				   		
   		data = $.trim(data);
		if (data.charAt(0) == "{"){			
			initRideData(JSON.parse(data));
			ridedata.sort(compareDateStr);
			listRides(ridedata);		
		}
		else{
			outputDiv("p", data);
		}
 	});			
}

//call getData function when page is initially loaded
$(function() {
	var pastrides = document.getElementById("pastrides");
	pastrides.checked=false;	
	getData();
});
